package com.atguigu.tingshu.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.NestedQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.TermsQueryField;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggest;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.CategoryFeignClient;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.PinYinUtils;
import com.atguigu.tingshu.model.album.AlbumAttributeValue;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.BaseCategory3;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import com.atguigu.tingshu.model.search.AttributeValueIndex;
import com.atguigu.tingshu.model.search.SuggestIndex;
import com.atguigu.tingshu.query.search.AlbumIndexQuery;
import com.atguigu.tingshu.search.repository.AlbumInfoIndexRepository;
import com.atguigu.tingshu.search.repository.SuggestIndexRepository;
import com.atguigu.tingshu.search.service.SearchService;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.search.AlbumInfoIndexVo;
import com.atguigu.tingshu.vo.search.AlbumSearchResponseVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.bytecode.ClassFileWriter;
import org.aspectj.weaver.ast.Var;
import org.springdoc.core.converters.ResponseSupportConverter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.suggest.Completion;
import org.springframework.data.elasticsearch.core.suggest.response.CompletionSuggestion;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;

import java.awt.image.Kernel;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Slf4j
@Service
@SuppressWarnings({"all"})
public class SearchServiceImpl implements SearchService {

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    private CategoryFeignClient categoryFeignClient;

    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Autowired
    private AlbumInfoIndexRepository albumInfoIndexRepository;

    @Autowired
    private ResponseSupportConverter responseSupportConverter;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private SuggestIndexRepository suggestIndexRepository;



    // 关键字自动补全
    @Override
    public List<String> completeSuggest(String keyword) throws IOException {
        SearchRequest.Builder requestBuilder = new SearchRequest.Builder();
        //dsl语句
        requestBuilder.index("suggestinfo").suggest(
                s->s.suggesters("suggestionKeyword",
                                f->f.prefix(keyword).completion(
                                        c->c.field("keyword")
                                                .skipDuplicates(true)
                                                .size(10)
                                                .fuzzy(f1->f1.fuzziness("auto"))))
                        .suggesters("suggestionkeywordPinyin",
                                f->f.prefix(keyword).completion(
                                        c->c.field("keywordPinyin")
                                                .skipDuplicates(true)
                                                .size(10)
                                                .fuzzy(f1->f1.fuzziness("auto"))))
                        .suggesters("suggestionkeywordSequence",f->f.prefix(keyword).completion(
                                c->c.field("keywordSequence").skipDuplicates(true).size(10)
                                        .fuzzy(z->z.fuzziness("auto"))
                        ))
        );
        //调用elasticsearchClient里面方法搜索
        SearchResponse<SuggestIndex> response =
                elasticsearchClient.search(requestBuilder.build(), SuggestIndex.class);

        HashSet<String> titleSet = new HashSet<>();
        titleSet.addAll(this.parseResultData(response,"suggestionKeyword"));
        titleSet.addAll(this.parseResultData(response,"suggestionkeywordPinyin"));
        titleSet.addAll(this.parseResultData(response,"suggestionkeywordSequence"));

        //如果查询Completion没有达到10条匹配，根据title做普通匹配
        if(titleSet.size()<10) {
            SearchResponse<SuggestIndex> searchResponse =
                    elasticsearchClient.search(s -> s.index("suggestinfo")
                                    .query(f -> f.match(m -> m.field("title").query(keyword)))
                            , SuggestIndex.class);
            //  从查询结果集中获取数据
            for (Hit<SuggestIndex> hit : response.hits().hits()) {
                //  获取数据结果
                SuggestIndex suggestIndex = hit.source();
                //  获取titile
                titleSet.add(suggestIndex.getTitle());
                //  判断当前这个结合的长度.
                if (titleSet.size()==10){
                    break;
                }
            }
        }
        return new ArrayList<>(titleSet);
    }
    //处理结果
    private List<String> parseResultData(SearchResponse<SuggestIndex> response,
                                         String suggestionKeyword) {
        List<String> suggestList = new ArrayList<>();
        Map<String, List<Suggestion<SuggestIndex>>> map = response.suggest();
        //根据名称获取值
        List<Suggestion<SuggestIndex>> suggestions = map.get(suggestionKeyword);
        suggestions.forEach(item -> {
            CompletionSuggest<SuggestIndex> completionSuggest =  item.completion();
            completionSuggest.options().forEach(it -> {
                SuggestIndex suggestIndex = it.source();
                suggestList.add(suggestIndex.getTitle());
            });
        });
        //  返回集合列表
        return suggestList;
    }


    // 首页数据
    @Override
    public List<Map<String, Object>> channel(Long category1Id) throws Exception{

        //1 远程调用：根据一级分类id 获取7个置顶的三级分类id
        Result<List<BaseCategory3>> topBaseCategory3Result = categoryFeignClient.findTopBaseCategory3(category1Id);
        List<BaseCategory3> baseCategory3List = topBaseCategory3Result.getData();

        //List<BaseCategory3>  -- Map<三级分类id，三级分类对象>
        Map<Long, BaseCategory3> category3Map = baseCategory3List.stream().collect(
                Collectors.toMap(BaseCategory3::getId,
                        BaseCategory3 -> BaseCategory3));

        // 获取到三级分类id
        List<Long> category3IdList = baseCategory3List.stream().map(BaseCategory3::getId).collect(Collectors.toList());

        // List<Long> -- List<FieldValue>
        List<FieldValue> idValueList = category3IdList.stream().map(id -> FieldValue.of(id)).collect(Collectors.toList());

        // 2 编写DSL语句查询es
        SearchRequest.Builder requestBuilder = new SearchRequest.Builder();
        requestBuilder.index("albuminfo").query(
                q->q.terms(
                        f->f.field("category3Id")
                                .terms(
                                        new TermsQueryField.Builder().value(idValueList).build()
                                )
                )
        );
        requestBuilder.aggregations("groupByCategory3IdAgg",
                a->a.terms(f->f.field("category3Id").size(10))
                        .aggregations("topTenHotScoreAgg",
                                a1->a1.topHits(
                                        s->s.size(6)
                                                .sort(o->o.field(o1->o1.field("hotScore")
                                                        .order(SortOrder.Desc)))))
        );
        SearchResponse<AlbumInfoIndex> response = elasticsearchClient.search(requestBuilder.build(), AlbumInfoIndex.class);


        // 3 从es查询返回结果获取需要数据，封装到map即可
        // 声明集合
        List<Map<String, Object>> result = new ArrayList<>();
        // 从聚合中获取数据
        Aggregate groupByCategory3IdAgg = response.aggregations().get("groupByCategory3IdAgg");
        groupByCategory3IdAgg.lterms().buckets().array().forEach(item->{
            // 创建集合数据
            List<AlbumInfoIndex> albumInfoIndexList = new ArrayList<>();
            // 获取三级分类对象id 对象
            long category3Id = item.key();
            // 获取要置顶的集合数据
            Aggregate topTenHotScoreAgg = item.aggregations().get("topTenHotScoreAgg");
            // 循环遍历获取聚合中的数据
            topTenHotScoreAgg.topHits().hits().hits().forEach(hit->{
                // 获取到source的json字符串数据
                String json = hit.source().toString();
                // 将json字符串转换为AlbumInfoIndex 对象
                AlbumInfoIndex albumInfoIndex = JSON.parseObject(json, AlbumInfoIndex.class);
                // 将对象添加到集合中
                albumInfoIndexList.add(albumInfoIndex);
            });

            // 声明一个map集合数据
            Map<String,Object> map = new HashMap<>();

            // 存储根据三级分类id要找的三级分类
            map.put("baseCategory3",category3Map.get(category3Id));

            // 存储所有专辑集合数据
            map.put("list",albumInfoIndexList);

            // 将map添加到集合中
            result.add(map);

        });
        return result;
    }



    // 专辑检索接口
    @Override
    public AlbumSearchResponseVo search(AlbumIndexQuery albumIndexQuery) throws Exception{

        //  构建dsl语句
        SearchRequest request = this.buildQueryDsl(albumIndexQuery);
        SearchResponse<AlbumInfoIndex> response = elasticsearchClient.search(request, AlbumInfoIndex.class);

        AlbumSearchResponseVo responseVO = this.parseSearchResult(response);
        //  分页信息
        responseVO.setPageNo(albumIndexQuery.getPageNo());
        responseVO.setPageSize(albumIndexQuery.getPageSize());
        //总页数
        // 总页数 =（总记录数 + 每页显示记录数 -1）/ 每页显示记录数
        long totalPages = (responseVO.getTotal() + albumIndexQuery.getPageSize() - 1) / albumIndexQuery.getPageSize();
        responseVO.setTotalPages(totalPages);
        return responseVO;
    }


    //把es查询返回SearchResponse处理，封装到AlbumSearchResponseVo
    private AlbumSearchResponseVo parseSearchResult(SearchResponse<AlbumInfoIndex> response) {

        // 创建vo对象
        AlbumSearchResponseVo searchResponseVo = new AlbumSearchResponseVo();
        // 获取总记录数
        HitsMetadata<AlbumInfoIndex> hits = response.hits();
        long totalValue = hits.total().value();
        // 设置到vo对象里面
        searchResponseVo.setTotal(totalValue);

        // 获取数据集合
        List<Hit<AlbumInfoIndex>> subHits = hits.hits();
        if (!CollectionUtils.isEmpty(subHits)){
            List<AlbumInfoIndexVo> list = subHits.stream().map(albumInfoIndexHit -> {
                AlbumInfoIndexVo albumInfoIndexVo = new AlbumInfoIndexVo();
                // 获取返回具体值部分
                AlbumInfoIndex albumInfoIndex = albumInfoIndexHit.source();
                BeanUtils.copyProperties(albumInfoIndex, albumInfoIndexVo);
                // 判断用户是否根据关键词进行检索
                if (null != albumInfoIndexHit.highlight().get("albumTitle")) {
                    // 获取高亮数据
                    String albumTitle = albumInfoIndexHit.highlight().get("albumTitle").get(0);
                    //赋值高亮语句
                    albumInfoIndexVo.setAlbumTitle(albumTitle);

                }
                return albumInfoIndexVo;
            }).collect(Collectors.toList());
            // 设置到vo对象里面
            searchResponseVo.setList(list);
        }
        return searchResponseVo;
    }

    //构建dsl语句，返回SearchRequest对象
    private SearchRequest buildQueryDsl(AlbumIndexQuery albumIndexQuery) {
        //创建SearchRequestBuilder
        SearchRequest.Builder requestBuilder = new SearchRequest.Builder();
        //requestBuilder构建dsl语句
        //创建BoolQuery对象
        BoolQuery.Builder boolQuery = new BoolQuery.Builder();
        //获取关键词
        //{ bool - should - match - albumTitle:值}
        String keyword = albumIndexQuery.getKeyword();
        if(!StringUtils.isEmpty(keyword)) {
            boolQuery.should(s->s.match(f->f.field("albumTitle").query(keyword)));
            boolQuery.should(s->s.match(f->f.field("albumIntro").query(keyword)));

            //高亮显示
            requestBuilder.highlight(h->h.fields("albumTitle",
                    f->f.preTags("<span style=color:red>").postTags("</span>")));
        }

        //{ bool - filter - term - category3Id:值}
        Long category3Id = albumIndexQuery.getCategory3Id();
        if(!StringUtils.isEmpty(category3Id)) {
            boolQuery.filter(s->s.term(f->f.field("category3Id").value(category3Id)));
        }
        //  一级分类Id
        Long category1Id = albumIndexQuery.getCategory1Id();
        if (!StringUtils.isEmpty(category1Id)) {
            boolQuery.filter(f -> f.term(s -> s.field("category1Id").value(category1Id)));
        }
        //  二级分类Id
        Long category2Id = albumIndexQuery.getCategory2Id();
        if (!StringUtils.isEmpty(category2Id)) {
            boolQuery.filter(f -> f.term(s -> s.field("category2Id").value(category2Id)));
        }

        //  属性id:属性值id
        List<String> attributeList = albumIndexQuery.getAttributeList();
        if(!CollectionUtils.isEmpty(attributeList)) {
            for(String attribute : attributeList) {
                //属性id:属性值id
                String[] split = attribute.split(":");
                if (null != split && split.length == 2) {
                    NestedQuery nestedQuery = NestedQuery.of(
                            f->f.path("attributeValueIndexList")
                                    .query(
                                            q->q.bool(
                                                    m->m.must(
                                                                    t->t.term(
                                                                            f1->f1.field("attributeValueIndexList.attributeId").value(split[0])
                                                                    ))
                                                            .must(
                                                                    t->t.term(
                                                                            f1->f1.field("attributeValueIndexList.valueId").value(split[1])
                                                                    ))
                                            )));

                    boolQuery.filter(f->f.nested(nestedQuery));
                }
            }
        }

        //排序
        //综合排序1   播放量2  发布时间3
        //	1:asc    2:desc  3:desc
        String order = albumIndexQuery.getOrder();
        if(!StringUtils.isEmpty(order)) {
            String[] split = order.split(":");
            //  定义一个排序字段
            String orderField = "";
            //  定义一个排序规则
            String sort = "";
            // split[0]   split[1]
            if(split != null && split.length == 2) {
                //根据 split[0]  1 2 3判断得到对应排序字段
                switch (split[0]) {
                    case "1":
                        orderField="hotScore";
                        break;
                    case "2":
                        orderField = "playStatNum";
                        break;
                    case "3":
                        orderField = "createTime";
                        break;
                }
                //排序规则 asc  desc
                sort = split[1];
            }
            String finalSort = sort;
            String finalOrderField = orderField;
            //排序dsl语句
            requestBuilder.sort(f->f.field(f1->f1.field(finalOrderField)
                    .order("asc".equals(finalSort)?SortOrder.Asc:SortOrder.Desc)));

        } else {//默认排序方式
            //  默认排序规则 _score
            requestBuilder.sort(f->f.field(o->o.field("_score").order(SortOrder.Desc)));
        }

        //  字段选择
        requestBuilder.source(s->s.filter(f->f.excludes("attributeValueIndexList")));

        //  分页： (pageNo-1)*pageSize()
        Integer from = (albumIndexQuery.getPageNo() - 1)*albumIndexQuery.getPageSize();
        requestBuilder.from(from);
        requestBuilder.size(albumIndexQuery.getPageSize());

        //{albuminfo -- query -- bool -- boolQuery}
        requestBuilder.index("albuminfo")
                .query(f->f.bool(boolQuery.build()));

        //requestBuilder的build返回SearchRequest
        SearchRequest searchRequest = requestBuilder.build();
        System.out.println("dsl: "+searchRequest.toString());
        return searchRequest;
    }


    // 根据专辑id实现上架
    @Override
    public void upperAlbum(Long albumId) {

        // 调用5个远程调用接口，得到返回数据
        // 根据专辑id获取专辑信息
        Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfo = albumInfoResult.getData();
        //if(albumInfo == null) {
        //    throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        //}
        // 断言判断：专辑信息不能为空
        Assert.notNull(albumInfo, "专辑信息不能为空");

        // 从专辑信息获取三级分类id，根据三级分类id获取一级和二级分类数据
        Long category3Id = albumInfo.getCategory3Id();
        Result<BaseCategoryView> categoryViewResult = categoryFeignClient.getCategoryView(category3Id);
        BaseCategoryView baseCategoryView = categoryViewResult.getData();
        Assert.notNull(baseCategoryView, "分类信息不能为空");

        //根据专辑id获取四个统计数据
        Result<Map<String, Object>> albumInfoStatResult = albumInfoFeignClient.getAlbumInfoStat(albumId);
        Map<String, Object> map = albumInfoStatResult.getData();

        //根据专辑id获取标签名称和标签值数据列表
        Result<List<AlbumAttributeValue>> albumAttributeValueResult = albumInfoFeignClient.findAlbumAttributeValue(albumId);
        List<AlbumAttributeValue> albumAttributeValueList = albumAttributeValueResult.getData();

        // 从专辑信息获取userId，根据userId获取用户信息
        Long userId = albumInfo.getUserId();
        Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
        UserInfoVo userInfoVo = userInfoVoResult.getData();
        // 断言判断：用户信息不能为空
        Assert.notNull(userInfoVo, "用户信息不能为空");

        // 2 把五个远程接口获取数据封装AlbumInfoIndex实体类
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();
        // 属性拷贝
        BeanUtils.copyProperties(albumInfo, albumInfoIndex);

        // 封装baseCategoryView 一级二级三级分类
        Long category1Id = baseCategoryView.getCategory1Id();
        Long category2Id = baseCategoryView.getCategory2Id();
        albumInfoIndex.setCategory1Id(category1Id);
        albumInfoIndex.setCategory2Id(category2Id);
        albumInfoIndex.setCategory3Id(category3Id);

        // 四个统计数据
        //Integer playStatNum = (Integer) map.get("playStatNum");
        //albumInfoIndex.setPlayStatNum(playStatNum);
        //TODO 为了测试方便，四个统计数据随机数
        //更新统计量与得分，默认随机，方便测试
        int num1 = new Random().nextInt(1000);
        int num2 = new Random().nextInt(100);
        int num3 = new Random().nextInt(50);
        int num4 = new Random().nextInt(300);
        albumInfoIndex.setPlayStatNum(num1);
        albumInfoIndex.setSubscribeStatNum(num2);
        albumInfoIndex.setBuyStatNum(num3);
        albumInfoIndex.setCommentStatNum(num4);
        double hotScore = num1*0.2 + num2*0.3 + num3*0.4 + num4*0.1;
        //  设置热度排名
        albumInfoIndex.setHotScore(hotScore);

        // 封装标签名称和标签值 List<AlbumAttributeValue> albumAttributeValueList
        // List<AlbumAttributeValue> --  List<AttributeValueIndex>
        if (!CollectionUtils.isEmpty(albumAttributeValueList)){
            List<AttributeValueIndex> attributeValueIndexList = albumAttributeValueList.stream().map(albumAttributeValue -> {
                AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                return attributeValueIndex;
            }).collect(Collectors.toList());
            albumInfoIndex.setAttributeValueIndexList(attributeValueIndexList);
        }

        // 封装用户信息
        // 赋值主播名称
        albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());

        // 3 调用AlbumInfoIndexRepository的save方法实现添加
        albumInfoIndexRepository.save(albumInfoIndex);

        //添加数据到suggestinfo索引库，后面实现自动补全
        SuggestIndex suggestIndex = new SuggestIndex();
        //id
        suggestIndex.setId(UUID.randomUUID().toString().replaceAll("-",""));
        //专辑标题
        suggestIndex.setTitle(albumInfoIndex.getAlbumTitle());
        //标题中文
        suggestIndex.setKeyword(new Completion(new String[]{albumInfoIndex.getAlbumTitle()}));
        //中文的完整汉语拼音，比如xiaoshuo
        suggestIndex.setKeywordPinyin(new Completion(new String[]{PinYinUtils.toHanyuPinyin(albumInfoIndex.getAlbumTitle())}));
        //中文的汉语拼音首字母，比如xs
        suggestIndex.setKeywordSequence(new Completion(new String[]{PinYinUtils.getFirstLetter(albumInfoIndex.getAlbumTitle())}));

        this.suggestIndexRepository.save(suggestIndex);



    }

    // 改造成并行方式实现专辑上架


    public void upperAlbum1(Long albumId){
        AlbumInfoIndex albumInfoIndex = new AlbumInfoIndex();

        //根据专辑id获取专辑信息
        CompletableFuture<AlbumInfo> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            Result<AlbumInfo> albumInfoResult = albumInfoFeignClient.getAlbumInfo(albumId);
            AlbumInfo albumInfo = albumInfoResult.getData();
            Assert.notNull(albumInfo, "专辑信息不饿能为空");

            // 封装到AlbumInfoIndex实体类
            BeanUtils.copyProperties(albumInfo, albumInfoIndex);
            return albumInfo;
        },threadPoolExecutor);

        //获取分类数据
        //专辑获取之后执行
        CompletableFuture<Void> completableFuture2 = completableFuture1.thenAcceptAsync(albumInfo -> {
            //获取三级分类id
            Long category3Id = albumInfo.getCategory3Id();
            Result<BaseCategoryView> categoryViewResult = categoryFeignClient.getCategoryView(category3Id);
            BaseCategoryView baseCategoryView = categoryViewResult.getData();
            Assert.notNull(baseCategoryView, "分类信息不能为空");
            // 封装三个分类id到albumInfoIndex
            Long category1Id = baseCategoryView.getCategory1Id();
            Long category2Id = baseCategoryView.getCategory2Id();
            albumInfoIndex.setCategory1Id(category1Id);
            albumInfoIndex.setCategory2Id(category2Id);
            albumInfoIndex.setCategory3Id(category3Id);
        }, threadPoolExecutor);
        // 获取专辑对应的标签数据
        CompletableFuture<Void> completableFuture3 = CompletableFuture.runAsync(() -> {
            Result<List<AlbumAttributeValue>> albumAttributeValueResult = albumInfoFeignClient.findAlbumAttributeValue(albumId);
            List<AlbumAttributeValue> albumAttributeValueList = albumAttributeValueResult.getData();
            // 封装 albumInfoIndex
            // List<AlbumAttributeValue> -->  List<AttributeValueIndex>
            if (!CollectionUtils.isEmpty(albumAttributeValueList)) {

                albumAttributeValueList.stream().map(albumAttributeValue -> {
                    AttributeValueIndex attributeValueIndex = new AttributeValueIndex();
                    BeanUtils.copyProperties(albumAttributeValue, attributeValueIndex);
                    return attributeValueIndex;
                }).collect(Collectors.toList());
            }
        },threadPoolExecutor);

        // 获取用户信息
        CompletableFuture<Void> completableFuture4 = completableFuture1.thenAcceptAsync(albumInfo -> {
            Long userId = albumInfo.getUserId();
            Result<UserInfoVo> userInfoVoResult = userInfoFeignClient.getUserInfoVo(userId);
            UserInfoVo userInfoVo = userInfoVoResult.getData();
            // 封装 albumInfoIndex
            albumInfoIndex.setAnnouncerName(userInfoVo.getNickname());
        }, threadPoolExecutor);


        // 赋值：初始化统计信息
        int playStatNum = new Random().nextInt(100000);
        int subscribeStatNum = new Random().nextInt(100000000);
        int buyStatNum = new Random().nextInt(10000000);
        int commentStatNum = new Random().nextInt(1000000000);
        albumInfoIndex.setPlayStatNum(playStatNum);
        albumInfoIndex.setSubscribeStatNum(subscribeStatNum);
        albumInfoIndex.setBuyStatNum(buyStatNum);
        albumInfoIndex.setCommentStatNum(commentStatNum);

        // 等待所有任务都完成，汇总
        CompletableFuture.allOf(
                completableFuture1,
                completableFuture2,
                completableFuture3,
                completableFuture4
        ).join();

        // 调用方法添加es
        albumInfoIndexRepository.save(albumInfoIndex);




    }

    // 根据专辑id实现下架
    @Override
    public void lowerAlbum(Long albumId) {
        albumInfoIndexRepository.deleteById(albumId);
    }



}
